# == Schema Information
#
# Table name: categories
#
#  id               :integer          not null, primary key
#  title            :string
#  weight           :integer          default(0)
#  products_counter :integer          default(0)
#  ancestry         :string
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#  code             :string
#  icon             :string
#

class Category < ApplicationRecord
  validates :title, presence: { message: "名称不能为空" }
  validates :title,uniqueness: { scope: [:ancestry], message: "名称不能重复" }

  has_ancestry orphan_strategy: :destroy

  has_many :products#, dependent: :destroy

  module FlOOR_CONST
    FLOOR = "floor"
    FIRST = "1st"
    SECOND = "2nd"
    THIRD = "3rd"
    FOURTH = "4th"
    FIFTH = "5th"
  end

  before_validation :correct_ancestry

  def is_floor?
    self.code == FlOOR_CONST::FLOOR
  end

  class << self

    def grouped_data
      self.roots.order("weight desc").inject([]) do |result, parent|
        row = []
        row << parent
        row << parent.children.order("weight desc")
        result << row
      end
    end

    def get_floor_category
      Category.where(code: FlOOR_CONST::FLOOR).first
    end

    def get_spaces
      space = Category.where(code: FlOOR_CONST::FLOOR).first
      Category.where(ancestry: space.id)
    end

  end


  private
  def correct_ancestry
    self.ancestry = nil if self.ancestry.blank?
  end


end
